package com.eazy.lksy.web.shiro;

import java.util.*;

import com.eazy.lksy.web.core.SpringContext;
import com.eazy.lksy.web.model.Role;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import com.eazy.lksy.web.model.User;
import com.eazy.lksy.web.service.PermissionService;
import com.eazy.lksy.web.service.RoleService;
import com.eazy.lksy.web.service.UserService;


public class ShiroRealm extends AuthorizingRealm {  
	

	 @Autowired
	 private RoleService roleService;
	 @Autowired
	 private PermissionService permissionService;
	 

    @Override  
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals){
        String userId = (String) principals.getPrimaryPrincipal().toString();
        Set<String> roleList = new HashSet<>();
        Set<String> permissionList = new HashSet<>();
        RoleService roleService = SpringContext.getBean(RoleService.class);
        List<Map<String,Object>> roles = roleService.getRoles(userId);
        //实体类User中包含有用户角色的实体类信息
        if(null!=roles && roles.size()>0){
            //获取当前登录用户的角色
            for(Map<String,Object> role : roles){
                  roleList.add(role.get("NAME") + "");
                  //实体类Role中包含有角色权限的实体类信息
                  List<Map<String,Object>> permission = permissionService.permissions(role.get("ID") + "");
                  if(null!=permission && permission.size()>0){
                      //获取权限
                      for(Map<String,Object> pmss : permission){
                          if(!StringUtils.isEmpty(pmss.get("PERM_CODE") + "")){
                              permissionList.add(pmss.get("PERM_CODE") + "");
                          }
                      }
                  }
              }
          }

        //为当前用户设置角色和权限
        SimpleAuthorizationInfo simpleAuthorInfo = new SimpleAuthorizationInfo();
        simpleAuthorInfo.setRoles(roleList);
        simpleAuthorInfo.setStringPermissions(permissionList);
        return simpleAuthorInfo;
    }  
   

    @Override  
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken)authcToken;
        UserService userService = SpringContext.getBean(UserService.class);

        User user = userService.getUserByName(token.getUsername());
        return new SimpleAuthenticationInfo(user.getId(), user.getPassword(), this.getName());
    }


}